﻿using System;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls;
using Medianamik.Core.Logging;

namespace Medianamik.UI.Web.ModalWindows
{
    public partial class PurgeLogsWindow : BasePage
    {
        #region Properties
        public int LogCount
        {
            get
            {
                if (ViewState["LogCount"] == null)
                    ViewState["LogCount"] = LogEntryManager.CountLogEntries();
                return (int)ViewState["LogCount"];
            }
        }
        #endregion

        #region Events
        protected void Page_Load(object sender, EventArgs e)
        {
            Title = Resources("Medianamik_ResourceManagement", "PurgeLogs");
            if (!IsPostBack)
            {
                var elements = Core.Sugar.Utility.GetEnumElements<LogEntryType>();
                ddlLogType.Items.Add(new ListItem());
                foreach (var element in elements)
                {
                    ddlLogType.Items.Add(new ListItem(Resources("Medianamik_ConfigurationManagement", "LogEntryType_" + element.Value), element.Key.ToString()));
                }
                btnPurge.Attributes.Add("onclick", "return confirmClose()");
            }
            RefreshStatusLabel(sender, e);
        }

        protected void PurgeLogs(object sender, EventArgs e)
        {
            LogEntryManager.PurgeLogEntries(MakeCondition());
            ScriptManager.RegisterStartupScript(this, typeof(PurgeLogsWindow),
                    "CloseWindow", "closeWindow();", true);
        }

        protected void RefreshStatusLabel(object sender, EventArgs e)
        {
            var toBeErased = LogEntryManager.CountLogEntries(MakeCondition());
            lblstatus.Text = string.Format(Resources("Medianamik_ConfigurationManagement", "ToBeErasedMessage"),
                                               toBeErased, LogCount);
        }
        #endregion

        #region Methods
        protected IDictionary<string, object> MakeCondition()
        {
            var condition = new Dictionary<string, object>();
            int logType;
            if(ddlLogType.SelectedIndex != 0 && int.TryParse(ddlLogType.SelectedValue, out logType))
                condition.Add("Type", logType);
            DateTime? begins = datDebut.SelectedDate;
            DateTime? ends = datFin.SelectedDate;
            if (begins.HasValue || ends.HasValue)
            {
                var pair = new Pair();
                if (begins.HasValue)
                    pair.First = begins;
                if (ends.HasValue)
                    pair.Second = ends.Value.AddDays(1).AddSeconds(-1);
                condition.Add("CreatedOn", pair);
            }
            return condition;
        }
        #endregion
    }
}
